
public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode right;
        public TreeNode left;

        public TreeNode(char val) {
            this.val = val;
        }
    }


    //手动创建一颗二叉树
    public TreeNode creatTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }


    //前序遍历 ---- 根左右
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }

        System.out.print(root.val + "->");
        preOrder(root.left);
        preOrder(root.right);
    }

    //中序遍历 --- 左根右
    public void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + "->");
        inOrder(root.right);
    }


    //后序遍历 --- 左右根
    public void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + "->");
    }


    //获取二叉树中结点的个数 --- 可以利用前序遍历，到根节点就count++
    public int size(TreeNode root) {
        if(root == null) {
            return 0;
        }

        return size(root.left) + size(root.right) + 1;
    }


    int count = 0;
    public int getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return 0;
        }

        if(root.left == null && root.right == null) {
            count++;
        }

        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
        return count;
    }


    public int getKLeveNodeCount(TreeNode root, int k) {
        if(root == null) {
            return 0;
        }

        if(k == 1) {
            return 1;//第一层
        }

        return getKLeveNodeCount(root.left, k-1) + getKLeveNodeCount(root.right, k-1);
    }

    public int getHight(TreeNode root) {
        if(root == null) {
            return 0;
        }

        int leftHight = getHight(root.left);
        int rightHight = getHight(root.right);

        return (Math.max(leftHight, rightHight) + 1);
    }



    public TreeNode find(TreeNode root, int val) {
        if(root == null) {
            return null;
        }

        if(root.val == val) {
            return root;
        }

        TreeNode ret = find(root.left, val);
        if(ret != null) {
            return ret;//在左子树找到了
        }

        ret = find(root.right, val);
        if(ret != null) {
            return ret;//在右子树找到了
        }

        return null;//左右子树都没找到
    }

}


